package com.health.system.action.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.health.system.javacommon.util.EncodeDecodeUtil;
import com.health.system.springSecurity.LogonUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;
import com.health.system.javacommon.jquery.JqueryPageHelper;
import com.health.system.javacommon.jquery.ListRange;
import com.health.system.javacommon.util.StringTool;

import com.health.system.model.organiza.DataOrganizations;
import com.health.system.model.system.Role;
import com.health.system.model.system.User;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;
import static com.health.system.javacommon.util.Struts2JsonHelper.*;


import com.health.system.javacommon.base.*;

import com.health.system.model.system.*;
import com.health.system.dao.system.*;
import com.health.system.service.system.impl.*;
import com.health.system.service.system.*;
import com.health.system.springSecurity.UserInfo;

/**
 * <p>Title: 系统操作员管理 Action</p> 
 * <p>用户基本信息表 TG_USER_INFO</p>
 * <p>Description: 页面通过Ajax调用Action层,返回JSONO数据</p>
 * Copyright: Copyright (c) 2011-03 
 * Company: 
 * 
 * @author  
 * @version 1.0 
*/

public class UserAction extends BaseStruts2Action {
	
	private UserManager userManager;
	private UserRoleManager userRoleManager;
	
	/** 通过spring自动注入 */
	public void setUserManager(UserManager manager) {
		this.userManager = manager;
	}	
	
	/** 通过spring自动注入 */
	public void setUserRoleManager(UserRoleManager manager) {
		this.userRoleManager = manager;
	}	
	
	/**
	 * jqGrid使用列表
	 * @throws IOException
	 */
	public void list() throws IOException{
		PageRequest<Map> pr = JqueryPageHelper.createPageRequestForJquery(getRequest());
		/**增加当前操作员机构信息*/
		Map mapParam = pr.getFilters();
		/**从登录用户类中取当前用户信息*/
		com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
		mapParam.put("userOrganId", userInfo.getCpId());
		Page page = userManager.findByPageRequest(pr);
		
		List<User> Userlist = (List) page.getResult();
		ListRange<User> resultList = new ListRange<User>();
		
		User user =new User();
		UserRole userRole =new UserRole();
		
		int userl =Userlist.size();
		List<User> Userlist1 =new ArrayList();
		
        for (int i = 0; i < userl; i++) {
        	user =(User)Userlist.get(i);
        	List userRoleList =userRoleManager.getUserRoleList(user.getId());
        	int userrolel =userRoleList.size();
        	List roleNew = new ArrayList();
        	for (int j = 0; j < userrolel; j++) {
        		userRole =(UserRole)userRoleList.get(j);
        		roleNew.add(userRole.getRoleId());
        	} 
        	user.setRoleIds(roleNew);
        	user.setPassword(EncodeDecodeUtil.base64Decode(user.getPassword()));
        	Userlist1.add(user);
		}

		resultList.setDataRows(Userlist1);
        resultList.setRecords(page.getTotalCount());
        resultList.setRows(page.getPageSize());
		if(page.getTotalCount()%page.getPageSize()>0){
			resultList.setTotal(page.getTotalCount() / page.getPageSize()+1);
		}else{
			resultList.setTotal(page.getTotalCount() / page.getPageSize());
		}
		resultList.setPage(pr.getPageNumber());
		outJson(resultList);
	}

	/**
	 * User添加
	 * @throws IOException
	 */
	public void save() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String userJson = request.getParameter("userJson");
			if (null != userJson&&!"".equals(userJson)) {
				JSONObject jsonobject =JSONObject.fromObject( userJson );
				User userobj = (User)JSONObject.toBean(jsonobject, User.class); 
				userobj.setLogincount(1);//登陆次数
				userManager.save(userobj);
				result.put("success", true);
				result.put("msg", "添加成功!");
			}else{
				result.put("success", false);
				result.put("msg", "添加失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "添加失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * User修改
	 * @throws IOException
	 */
	public void update() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
			try{
				HttpServletRequest request = getRequest();
				String userJson = request.getParameter("userJson");
				if (null != userJson&&!"".equals(userJson)) {
					JSONObject jsonobject =JSONObject.fromObject( userJson );
					User userobj = (User)JSONObject.toBean(jsonobject, User.class); 
					userobj.setId(jsonobject.get("id").toString());
					userManager.update(userobj);
					result.put("success", true);
					result.put("msg", "修改成功!");
				}else{
					result.put("success", false);
					result.put("msg", "修改失败 数据错误!");
				}
			}catch (Exception e){
				result.put("success", false);
				result.put("msg", "修改失败!");
				e.printStackTrace();
			}
		outJson(result);
	}
	
	/**
	 * User删除
	 * @throws IOException
	 */
	public void delete() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String ids = request.getParameter("ids");
			if (null != ids&&!"".equals(ids)){
				User user =new User();
				user.setIdList(StringTool.stringToArray(ids));
				userManager.removeByIdArry(user);
				result.put("success", true);
				result.put("msg", "删除成功");
			}else{
				result.put("success", false);
				result.put("msg", "删除失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "删除失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	/**
	 * 验证用户名
	 * @throws IOException
	 */
	public void checkUserName() throws IOException {
		try {
			HttpServletRequest request = getRequest();
			/**新增操作员账号*/
			String userName=getRequest().getParameter("userName");
			/**组织机构ID*/
			String company=getRequest().getParameter("company");
			Map<String, Object> parameter = new HashMap<String, Object>();
			
			parameter.put("name", userName);
			parameter.put("company", company);
			List list = userManager.findList(parameter);
			if(list!=null && list.size()>0){
				getResponse().getWriter().print(false);			
			}else{
				getResponse().getWriter().print(true);
		    }
		} catch (Exception e) {
			getResponse().getWriter().print(false);
			e.printStackTrace();
		}
	}
	
	public void getUserInfo() throws IOException{	 
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			//从登录用户类中取当前用户信息
			UserInfo userInfo = LogonUser.logonUser();
			String userId = "";
			if(null!=userInfo){
			   userId = userInfo.getUserId();
			}
			String id = request.getParameter("id");
			 
				User user =new User();
				user = userManager.getById(userId);
				result.put("success", true);
				result.put("msg", user);
			 
		}catch (Exception e){
			e.printStackTrace();
			result.put("success", false);
			result.put("msg", "删除失败!");
			e.printStackTrace();
		}
		outJson(result);
	}
	/**
	 * 操作员 修改 个人信息
	 * @throws IOException
	 */
	public void personal() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
			try{
				HttpServletRequest request = getRequest();
				String userJson = request.getParameter("userJson");
				if (null != userJson&&!"".equals(userJson)) {
					JSONObject jsonobject =JSONObject.fromObject( userJson );
					User userobj = (User)JSONObject.toBean(jsonobject, User.class); 
					userobj.setId(jsonobject.get("id").toString());
					userManager.personal(userobj);
					result.put("success", true);
					result.put("msg", "修改成功!");
				}else{
					result.put("success", false);
					result.put("msg", "修改失败 数据错误!");
				}
			}catch (Exception e){
				result.put("success", false);
				result.put("msg", "修改失败!");
				e.printStackTrace();
			}
		outJson(result);
	}
	
	/**
	 * <p>操作员下拉框</p>
	 * <p>查询当前操作员对应机构的操作员集合</p>
	 * @throws IOException
	 * @author bzq 
	 */
	public void getComboBox() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			List list =null;
			String str ="<option value=\"\">-请选择-</option>";
			User userObj =new User();
			//从登录用户类中取当前用户信息
			com.health.system.springSecurity.UserInfo userInfo = LogonUser.logonUser();
			String ec_id = "";
			if(null!=userInfo){
				ec_id = userInfo.getCpId();
			}
			Map map = new HashMap();
			//map.put("company", null);
			list = userManager.findList(map);
			
			for (int i = 0; list != null && i < list.size(); i++) {
				userObj = (User)list.get(i);
				str += "<option value=\"" + userObj.getId() + "\">" + userObj.getRealname() + "</option>";
			}
			result.put("success", true);
			result.put("msg", str);
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	
	/**
	 * <p>操作员下拉框</p>
	 * <p>查询当前操作员对应机构的操作员集合</p>
	 * @throws IOException
	 * @author bzq 
	 */
	public void getComboBoxIdea() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			
			HttpServletRequest request = getRequest();
			String reportJson = request.getParameter("reportJson");
			if (null != reportJson&&!"".equals(reportJson)) {
				List list =null;
				String str ="<option value=\"\">-请选择-</option>";
				User userObj =new User();	
				list = userManager.findList(new HashMap());
				
				for (int i = 0; list != null && i < list.size(); i++) {
					userObj = (User)list.get(i);					
					if(reportJson !=null && reportJson.equals(userObj.getId())){
						str += "<option value=\"" + userObj.getId() + "\" selected=" +"'selected'\">"
						+userObj.getRealname() + "</option>";
					}else{
						str += "<option value=\"" + userObj.getId() + "\">" + userObj.getRealname() + "</option>";
					}
				}					
				result.put("success", true);
				result.put("msg", str);
			}else{
				result.put("success", false);
				result.put("msg", "修改失败 数据错误!");
			}			
			
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "");
			e.printStackTrace();
		}
		outJson(result);
	}
	
	
	/**
	 * <p>用户密码重置</p>
	 * <p>对当前显示的用户重置密码</p>
	 * @throws IOException
	 * @author gm 
	 */
	public void resetPassword() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String userid = request.getParameter("useridJson");
			if (null != userid&&!"".equals(userid)) {
				User userobj = new User(); 
				userobj = userManager.getById(userid);
				userobj.setPassword("123456"); 
			 
				userManager.update(userobj);
				result.put("success", true);
				result.put("msg", "密码重置为:123456,成功!");
			}else{
				result.put("success", false);
				result.put("msg", "修改失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "修改失败!");
			e.printStackTrace();
		}
	  outJson(result);
	}
	
	/**
	 * <p>用户密码修改</p>
	 * <p>对当前显示的用户修改密码</p>
	 * @throws IOException
	 * @author gm 
	 */
	public void updatePassword() throws IOException{
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			HttpServletRequest request = getRequest();
			String userJson = request.getParameter("userJson");
			if (null != userJson&&!"".equals(userJson)) {
				JSONObject jsonobject =JSONObject.fromObject( userJson );
				User userobj = (User)JSONObject.toBean(jsonobject, User.class); 
				String pwd = userobj.getPassword();
				String pwd_new = userobj.getPasswordNew1();
				String pwd_new2 = userobj.getPasswordNew2();
				if(!pwd_new.equals(pwd_new2)){
					result.put("success", false);
					result.put("msg", "两次输入的密码不一致!");
					outJson(result);
					return;
				}
				UserInfo userInfo = LogonUser.logonUser();
				userobj = new User();
				String password = "";
				if(null!=userInfo){
					password = userInfo.getPassword();
					userobj.setId(userInfo.getUserId());
					userobj.setCompany(userInfo.getCpId());
				}
				pwd = EncodeDecodeUtil.base64Encode(pwd); 
				
				if(pwd.equals(password)){
					userobj.setPassword(pwd_new);
					userManager.update(userobj);
					
				}else{
					result.put("success", false);
					result.put("msg", "当前密码输入错误，请重新输入!");
					outJson(result);
					return;
				} 
				result.put("success", true);
				result.put("msg", "密码修改为:"+pwd_new2+",成功!");
			}else{
				result.put("success", false);
				result.put("msg", "修改失败 数据错误!");
			}
		}catch (Exception e){
			result.put("success", false);
			result.put("msg", "修改失败!");
			e.printStackTrace();
		}
	 outJson(result); 
	}
	
	/**
	 * 验证机构简称
	 * @throws IOException
	 */
	public void checkPassword() throws IOException {
		//机构简称
		System.out.println("验证机构简称");
		String password = "" ;
		try {
			
			HttpServletRequest request = getRequest();
			password=getRequest().getParameter("password");
			
			Map<String, Object> parameter = new HashMap<String, Object>();
			UserInfo userInfo = LogonUser.logonUser();
			password = EncodeDecodeUtil.base64Encode(password);
			parameter.put("password", password);
			parameter.put("id",  userInfo.getUserId());
			List list = userManager.findList(parameter);
			if(list!=null && list.size()>0){
				getResponse().getWriter().print(true);
			}else{
				getResponse().getWriter().print(false);
		    }
		} catch (Exception e) {
			getResponse().getWriter().print(false);
			e.printStackTrace();
		}
	}
 
}
